<template>
  <div class="threeMember" :class="formState.isEnable ? 'OpenthreeMember' : ''">
    <div class="tips">
      操作说明
      <a-tooltip placement="right">
        <template #title>
          <span>
            1.启用三员管理并勾选相应模块操作后，有权限人员在对该模块数据进行相应操作时将提交数据至安全管理员进行审核，审核通过后方生效；<br />
            2.给用户赋予安全管理员时请先为其添加三员审核菜单权限，赋予审计管理员角色时请先为其添加三员操作日志菜单权限；
          </span>
        </template>
        <span class="iconfont icon-hint1"></span>
      </a-tooltip>
    </div>
    <a-form :model="formState" autoComplete="off" labelAlign="right" ref="threeMemberForm">
      <a-form-item :label="formState.status_setting.label" :rules="[formState.status_setting.rule]">
        <a-switch :disabled="!btnPerm.includes('saveAble')" size="small" v-model:checked="formState['isEnable']"
          @change="checkoutStatus"></a-switch>
        <span class="isOpen">{{ formState["isEnable"] ? "是" : "否" }}</span>
      </a-form-item>
      <a-form-item label="" v-if="formState.isEnable">
        <div class="titleSetting">
          {{ formState.section }}
        </div>
      </a-form-item>
      <a-form-item :name="['securityManagers']" :label="formState.safeManager_setting.label"
        :rules="[formState.safeManager_setting.rule]" v-if="formState.isEnable">
        <a-input-group compact @click="selectMember('securityManagers')" class="a-input-group_manage">
          <a-input v-model:value="securityManagers" placeholder="请选择" class="selectInput" ref="securityManagers_ref" />
          <a-button type="primary">选择</a-button>
        </a-input-group>
      </a-form-item>
      <a-form-item name="auditManagers" :label="formState.auditManager_setting.label"
        :rules="[formState.auditManager_setting.rule]" v-if="formState.isEnable">
        <a-input-group compact @click="selectMember('auditManagers')" class="a-input-group_manage">
          <a-input v-model:value="auditManagers" placeholder="请选择" class="selectInput" ref="auditManagers_ref" />
          <a-button type="primary">选择</a-button>
        </a-input-group>
      </a-form-item>
      <a-form-item label="" v-if="formState.isEnable">
        <div class="useScope">应用模块</div>
      </a-form-item>
    </a-form>
    <template v-for="(item, index) in formState.moduleSetups" v-if="formState.isEnable">
      <div class="selection" :class="'selection' + index">
        <a-form-item :label="item.moduleName">
          <a-checkbox-group v-model:value="item.selectedOptions" :options="item.opSetups.map((data: any) => ({
            'label': data.opName, 'value': data.opId
          }))" />
        </a-form-item>
      </div>
    </template>
    <!-- 新建模态框 -->
    <base-modal :width="modAlProps.width" :isVisible="isVisible" :title="modAlProps.title" :buttons="buttons"
      @handleOk="buttonMessage" @handleCancle="(isVisible = false) && (selectOrgData = '') && (userName = '')"
      class="sensitive_modal" v-if="isVisible">
      <template v-slot:body>
        <div class="searchIptBox">
          <div class="searchIpt">
            <a-tree-select class="AtreeSelect" v-model:value="selectOrgData" ref="siteDetail_treeSelect" show-search
              :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }" placeholder="请选择" allow-clear
              treeNodeFilterProp="name" :fieldNames="{
                children: 'children',
                label: 'name',
                value: 'id',
              }" tree-default-expand-all :tree-data="OrgData" @select="selectOrgTreeData">
            </a-tree-select>
            <a-input-search v-model:value="userName" placeholder="用户名/真实姓名" enter-button @search="getUsers({})" />
          </div>
          <div class="yxyh">已选用户</div>
        </div>
        <a-transfer v-model:target-keys="targetKeys" :data-source="userData.records" :disabled="disabled"
          :show-search="showSearch" :show-select-all="false" @change="onChange" class="threeMembertransfer">
          <template #children="{
            direction,
            filteredItems,
            selectedKeys,
            disabled: listDisabled,
            onItemSelectAll,
            onItemSelect,
          }">
            <a-table rowKey="id" :row-selection="getRowSelection({
              disabled: listDisabled,
              selectedKeys,
              onItemSelectAll,
              onItemSelect,
            })
              " :columns="direction === 'left' ? leftColumns : rightColumns" :data-source="filteredItems" size="small"
              :style="{ pointerEvents: listDisabled ? 'none' : null }" :custom-row="({ key } = { key: any }) => ({
                onClick: () => {
                  if (listDisabled) return;
                  onItemSelect(key, !selectedKeys.includes(key));
                },
              })
                " />
          </template>
        </a-transfer>
      </template>
    </base-modal>
    <div class="table-bottom_fiexd" :style="styleWidth" v-if="formState.isEnable">
      <a-button type="primary" :disabled="!btnPerm.includes('saveAble')" @click="saveButton">保存</a-button>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, watch, onMounted, reactive, nextTick, computed } from "vue";
import request from "@/api/index";
import { useFixeWidth, styleWidth } from "@/hooks/useFixeWidth";
import baseModal from "@/components/modal/baseModal.vue";
import { any } from "vue-types";
import { message } from "ant-design-vue";
import { routerPerm } from '@/utils/common';

interface MockData {
  key: string;
  title: string;
  description: string;
  disabled: boolean;
}
type tableColumn = Record<string, string>;

//验证表单
const checksForm = async (_rule: dataSourceType = {}, value: any) => {
  console.log(_rule, value, "_rule");
  if (_rule.required) {
    if (value && value.length) {
      return Promise.resolve();
    } else {
      return Promise.reject(`${_rule.msg1}`);
    }
  } else {
    return Promise.resolve();
  }
};
const TableColumns = [
  {
    dataIndex: "userName",
    title: "用户名",
  },
  {
    dataIndex: "realName",
    title: "真实姓名",
  },
  {
    dataIndex: "orgName",
    title: "组织名称",
  },
];
interface MockData {
  key: string;
  title: string;
  description: string;
  disabled: boolean;
}
// interFace
interface dataSourceType {
  [propName: string]: any;
}
//data
const btnPerm = ref<any[]>([]);
const formState = ref<dataSourceType>({
  //   isEnable: false,
  status_setting: {
    params: "isEnable",
    label: "是否开启三员管理",
    rule: {
      required: false,
      trigger: ["blur"],
    },
  },
  securityManagers: [],
  safeManager_setting: {
    params: "securityManagers",
    label: "安全管理员",
    rule: {
      required: true,
      validator: checksForm,
      trigger: ["change", "blur"],
      msg1: "安全管理员不可为空！",
    },
  },
  auditManagers: [],
  auditManager_setting: {
    params: "auditManagers",
    label: "审计管理员",
    rule: {
      required: true,
      validator: checksForm,
      trigger: ["change", "blur"],
      msg1: "审计管理员不可为空！",
    },
  },
  section: "三员管理角色配置",
});
let securityManagers = ref("");
let auditManagers = ref("");
let securityManagers_ref = ref();
let auditManagers_ref = ref();
const modAlProps: dataSourceType = reactive({
  width: "1080",
  title: "选择用户",
});
const threeMemberForm = ref();
const isVisible = ref<Boolean>(false);
const buttons = ref<dataSourceType[]>([
  {
    text: "保存",
    "html-type": "submit",
    keepAlive: true,
    disabled: false,
  },
]); //模态框button按钮个数和文案修改

const targetKeys = ref<any[]>([]);
const disabled = ref<boolean>(false);
const showSearch = ref<boolean>(false);
const leftColumns = ref<tableColumn[]>(TableColumns);
const rightColumns = ref<tableColumn[]>(TableColumns);
const tempTargetKeys = ref<string[]>([]);
const allData = ref<dataSourceType[]>([]);

// methods
const onChange = (nextTargetKeys: string[]) => {
  console.log(nextTargetKeys, 'nextTargetKeys')
  tempTargetKeys.value = JSON.parse(JSON.stringify(nextTargetKeys));
};

const getRowSelection = ({
  disabled,
  selectedKeys,
  onItemSelectAll,
  onItemSelect,
}: Record<string, any>) => {
  return {
    preserveSelectedRowKeys: true,
    getCheckboxProps: (item: Record<string, string | boolean>) => ({
      disabled: disabled || item.disabled,
    }),
    onSelectAll(selected: boolean, selectedRows: Record<string, string | boolean>[]) {
      const treeSelectedKeys = selectedRows
        .filter((item) => !item.disabled)
        .map(({ key }) => key);
      onItemSelectAll(treeSelectedKeys, selected);
    },
    onSelect({ key }: Record<string, string>, selected: boolean) {
      onItemSelect(key, selected);
    },
    selectedRowKeys: selectedKeys,
  };
};
//穿梭框相关数据
const selectOrgData = ref("");
const OrgData = ref<dataSourceType[]>([]);
const userName = ref("");
const isSafa_audit = ref("");
let userData = reactive<dataSourceType>({
  records: [],
  total: "",
  size: "",
});
let saveData = ref({});
//watch
watch(
  () => tempTargetKeys.value,
  (newVal, oldVal) => {
    if (newVal && newVal.length) {
      buttons.value[0].disabled = false;
    } else {
      buttons.value[0].disabled = true;
    }
  }
);

//computed
securityManagers = computed(() =>
  formState.value.securityManagers.map((item: dataSourceType) => item.name).join(",")
);
auditManagers = computed(() =>
  formState.value.auditManagers.map((item: dataSourceType) => item.name).join(",")
);
saveData = computed(() => {
  let dataTemp = JSON.parse(JSON.stringify(formState.value));
  dataTemp.moduleSetups.forEach((item: dataSourceType) => {
    item.opSetups.forEach((opSetups: dataSourceType) => {
      opSetups.isEnable = item.selectedOptions.includes(opSetups.opId) ? true : false;
    });
  });
  dataTemp.auditManagers = dataTemp.auditManagers.map((item: dataSourceType) => item.id);
  dataTemp.securityManagers = dataTemp.securityManagers.map(
    (item: dataSourceType) => item.id
  );
  return dataTemp;
});

//methods
const checkoutStatus = () => {
  if (formState.value.isEnable) {
    openThreeMemberSetting();
  } else {
    closeThreeMemberSetting();
  }
};
const selectMember = (param: any) => {
  targetKeys.value = formState.value[param].map((item: dataSourceType) => item.id);
  fetchUserOrgTree();
  getUsers({});
  nextTick(() => {
    isVisible.value = true;
  });
  isSafa_audit.value = param;
};
const getThreeMemberSetting = async () => {
  // 调接口获取配置
  await request.fetchThreeMemberSetting({}).then((res: any) => {
    let data = res;
    let dataTemp = Object.assign(formState.value, data || {});
    dataTemp.moduleSetups.forEach((item: dataSourceType) => {
      let selectedOptions: any = [];
      item.opSetups.forEach((opSetups: dataSourceType) => {
        if (opSetups.isEnable) {
          selectedOptions.push(opSetups.opId);
        }
      });
      item.selectedOptions = selectedOptions;
    });
    formState.value = dataTemp;
    console.log(formState.value, "formState.value");
  });
};
const openThreeMemberSetting = async () => {
  // 调接口打开配置
  await request.openThreeMemberSetting({}).then((res: any) => {
    if (res.code == "00000 00000") {
      message.success(res.message);
    } else {
      message.error(res.message);
    }
  });
};
const closeThreeMemberSetting = async () => {
  await request.closeThreeMemberSetting({}).then((res: any) => {
    if (res.code == "00000 00000") {
      message.success(res.message);
    } else {
      message.error(res.message);
    }
  });
};
const buttonMessage = async (msg: dataSourceType) => {
  targetKeys.value = JSON.parse(JSON.stringify(tempTargetKeys.value));
  formState.value[isSafa_audit.value] = [];
  allData.value.forEach((item: dataSourceType) => {
    targetKeys.value.forEach((data: dataSourceType) => {
      if (data == item.id) {
        formState.value[isSafa_audit.value].push({
          id: item.id,
          name: item.userName,
        });
      }
    });
  });
  if (isSafa_audit.value == "securityManagers") {
    securityManagers_ref.value.focus();
    securityManagers_ref.value.blur();
  } else {
    auditManagers_ref.value.focus();
    auditManagers_ref.value.blur();
  }
  userName.value = '';
  selectOrgData.value = '';
  isVisible.value = false;
};
//获取当前用户可见组织树
const fetchUserOrgTree = async () => {
  const data = (await request.fetchUserOrgTree()) || [];

  OrgData.value = [
    { name: "全部组织", id: "" },
    ...data.filter((item: dataSourceType) => !item.authAble),
  ];
};
const getUsers = async (datas: dataSourceType) => {
  // 获取表格数据
  const data: {} = {
    pageNumber: datas.pageNumber || 0,
    pageSize: datas.pageSize || 100000000,
    name: userName.value,
    orgId: selectOrgData.value,
  };
  const telData = (await request.fetchUserPage(data)) || {};
  let reqData = telData;
  allData.value = allData.value.length ? allData.value : reqData.records;
  userData.total = reqData.total;
  userData.size = reqData.size;
  userData.records = reqData.records;
  userData.records.map((item: dataSourceType) => (item.key = item.id));
};
const selectOrgTreeData = () => {
  getUsers({});
};
const saveButton = () => {
  threeMemberForm.value
    .validate()
    .then(() => {
      request.updateThreeMemberSetting(saveData.value).then((res: dataSourceType) => {
        if ((res.code = "00000 00000")) {
          message.success(res.message);
        } else {
          message.error(res.message);
        }
      });
    })
    .catch((err: any) => {
      throw new Error(err);
    });
};
// onMounted
onMounted(() => {
  btnPerm.value = routerPerm();
  useFixeWidth();
  getThreeMemberSetting();
});
</script>

<style lang="less">
.threeMember {
  padding: 16px;
  background: #fff;
  height: calc(100% - 72px);
  overflow: auto;

  .tips {
    margin-bottom: 16px;
    font-size: 14px;
    color: #333;
  }

  .isOpen {
    margin-left: 8px;
  }

  .titleSetting {
    height: 40px;
    font-size: 14px;
    font-weight: 500;
    color: rgba(0, 0, 0, 0.85);
    line-height: 40px;
    background: #f7f8fa;
    border-radius: 2px 2px 2px 2px;
    position: relative;
    padding-left: 24px;
    margin-top: 24px;
  }

  .titleSetting:after {
    width: 3px;
    height: 12px;
    background: var(--theme_button_active_bg_color, #1050c7);
    border-radius: 0px 0px 0px 0px;
    opacity: 1;
    content: "";
    position: absolute;
    left: 3px;
    z-index: 1;
    top: 14px;
  }

  .selectInput {
    width: 300px;

    .ant-input {
      height: 32px;
      font-size: 14px;
      color: #333;
    }

    .ant-btn {
      height: 32px;
      font-size: 14px;
      color: #333;
    }
  }

  .useScope {
    margin-left: 24px;
  }

  .selection {
    .ant-form-item-label {
      width: 90px;
    }
  }

  .table-bottom_fiexd {
    height: 48px;
    display: flex;
    justify-content: center;
    align-items: center;
    position: fixed;
    bottom: 0;
    background: #fff;
    box-shadow: 0px -12px 48px 16px rgba(0, 0, 0, 0.03),
      0px -9px 28px 0px rgba(0, 0, 0, 0.05), 0px -6px 16px -8px rgba(0, 0, 0, 0.08);
  }
}

.OpenthreeMember {
  height: calc(100% - 120px);
}

.searchIptBox {
  display: flex;
  align-items: center;

  .yxyh {
    margin-left: 40px;
    margin-bottom: 24px;
  }
}

.searchIpt {
  width: calc(50% - 20px);
  display: flex;
  justify-content: space-between;
  margin-bottom: 24px;

  .ant-input-group-wrapper {
    width: 40%;
  }

  .ant-select {
    width: 50%;
  }
}

.threeMembertransfer {
  .ant-transfer-list-header {
    display: none;
  }
}

.a-input-group_manage {
  position: relative;
  width: 365px;
  cursor: pointer;
}

.a-input-group_manage::after {
  content: "";
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
}
</style>
